<template>
  <div>
    <!-- 1.0面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文章添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 2.0卡片 -->
    <el-card class="bodx-car">
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>

        <el-form-item label="栏目">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >

          <el-checkbox-group v-model="form.categories">
            <el-checkbox
              name="categories"
              v-for="item in cateList"
              :key="item.id"
              :label="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>

        <div style="margin: 15px 0"></div>
        <el-form-item label="类型">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">文章</el-radio>
            <el-radio :label="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文本" v-show="form.type == 1">
          <VueEditor :config="config" ref="vueEditor" />
        </el-form-item>
        <el-form-item label="视频" v-show="form.type == 2">
          <el-upload
            class="upload-demo"
            :file-list="videoList"
            :action="$baseURL + '/upload'"
            :headers="headers"
            :on-success="videosuccess"
            :before-upload="videobeforeupload"
            :before-remove="videobeforeremove"
            multiple
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传mp4视频文件，且不超过1m
            </div>
          </el-upload>
        </el-form-item>
        <!-- 上传封面 -->
        <el-form-item label="封面">
          <el-upload
            :file-list="form.cover"
            :action="$baseURL + '/upload'"
            list-type="picture-card"
            :headers="headers"
            :on-success="handlesuccess"
            :on-remove="onRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <!-- 提交 -->
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getToken } from "@/utils/tokenData.js";
import VueEditor from "vue-word-editor";
import "quill/dist/quill.snow.css";
import { postAPI, getPostDetailstAPI, updatePostAPI } from "@/apis/news.js";
import { getColumnListAPI } from "@/apis/index.js";

export default {
  async created() {
    //获取栏目
    const res = await getColumnListAPI();
    this.cateList = res.data.data.slice(2);
    // console.log(this.$baseURL);
    if (this.id) {
      const res2 = await getPostDetailstAPI(this.id);
      console.log(res2);
      const { title, type, categories, content, cover } = res2.data.data;
      this.form.title = title;
      this.form.categories = categories.map((item) => item.id);
      this.form.type = type;
      if (type == 1) {
        this.cver = this.$refs.vueEditor.editor.clipboard.dangerouslyPasteHTML(
          0,
          content
        );
      } else {
        this.videoList = [{ name: "mp4视频", url: content }];
      }
      this.form.cover = cover.map((item) => {
        return { name: item.id, url: this.$baseURL + item.url };
      });
    }
    //全选bug
    // if (this.cateList.length == this.form.categories.length) {
    //   this.isIndeterminate = false;
    //   this.checkAll = true;
    // }
  },
  data() {
    return {
      videoList: [],
      id: this.$route.params.id,
      form: {
        title: "",
        categories: [],
        content: "",
        cover: [],
        type: 1,
      },
      rules: {
        title: [
          { min: 3, max: 20, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },
      headers: { Authorization: getToken() },
      checkAll: false,
      isIndeterminate: true,
      cateList: [],
      config: {
        // 上传图片的配置
        uploadImage: {
          url: `${this.$baseURL}/upload`,
          headers: { Authorization: getToken() },
          name: "file",
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          //   uploadSuccess(res, insert) {
          //       console.log(res);
          //     // insert("http://localhost:3000" + res.data.url);
          //   },
          uploadSuccess: (res, insert) => {
            console.log(res);
            insert(this.$baseURL + res.data.data.url);
          },
        },
      },
    };
  },
  //富文本框
  components: {
    VueEditor,
  },
  methods: {
    //提交表单
    async onSubmit() {
      const { title, categories, content, cover, type } = this.form;
      if (title.trim() === "") {
        return this.$message.warning("标题不符合规则");
      }
      if (categories.length === 0) {
        return this.$message.warning("至少一个栏目");
      }
      if (cover.length === 0) {
        return this.$message.warning("至少一个封面");
      }
      if (content == "<p><br></p>") {
        return this.$message.warning("新闻标题不能为空");
      }
      this.form.content = this.$refs.vueEditor.editor.root.innerHTML;
      const data = {
        ...this.form,
        categories: this.form.categories.map((item) => {
          return { id: item };
        }),
        cover: this.form.cover.map((item)=>{
            return {id:item.name}
        })
      };
      const res = await updatePostAPI(this.id,data)
      console.log(res);
    //   if (this.id) {
    //        this.form.content = this.$refs.vueEditor.editor.root.innerHTML;
    //         const res = await postupdateAPI(this.id,data)
    //         console.log(res);
    //   } else {
    //     if (this.form.type == 1) {
    //       this.form.content = this.$refs.vueEditor.editor.root.innerHTML;
    //       // console.log("submit!", this.form);
    //       const res = await postAPI(data);
    //       if (res.data.message == "文章发布成功") {
    //         const tips = this.form.type == 1 ? "文章发布成功" : "视频发布成功";
    //         this.$message.success(tips);
    //         this.$router.push("/home/post_list");
    //       }
    //     }
    //   }
    },
    //全选和反选
    handleCheckAllChange(val) {
      console.log(val);
      this.form.categories = val ? this.cateList.map((item) => item.id) : [];
      this.isIndeterminate = false;
    },

    //封面
    handlesuccess(res) {
      console.log(res);
      //   this.form.cover.push({ id: res.data.id });
      this.form.cover.push({
        id: res.data.id,
        name: res.data.id,
        url: this.$baseURL + res.data.url,
      });
    },
    onRemove(file) {
      console.log(2222, "文件列表移除文件时的钩子", file);
      // 获取到 id
      const id = file.name;
      //   const id = file.response.data.id;
      //   // 图片删除了， id 也要被删除
      this.form.cover = this.form.cover.filter((item) => item.name !== id);
    },
    // handremove(file){
    //     const id = file.response.data.id;
    //      this.form.cover=this.form.cover.filter(item=>item.id !=id)
    // },
    // 视频

    //上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
    videobeforeupload(file) {
      console.log(file);
      if (file.type != "video/mp4" || file.size >= 1024 * 1024) {
        this.$message.warning("视频格式或者大小不对");
        return false;
      }
    },
    videosuccess(res) {
      this.form.content = this.$baseURL + res.data.url;
    },
    videobeforeremove() {
      this.form.content = "";
    },
  },
  watch: {
    "form.categories"(value) {
      let checkedCount = value.length;
      //   console.log(checkedCount);
      this.checkAll = checkedCount === this.cateList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cateList.length;
    },
  },
};
</script>

<style lang="less" scoped>
.bodx-car {
  margin-top: 20px;
}
</style>